<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>半导体PN结与激光器原理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #0d1b2a, #1b3a4b, #2c5282);
            color: white;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1600px;
            margin: 0 auto;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 25px;
            background: rgba(13, 27, 42, 0.7);
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
            border: 1px solid #3498db;
        }
        
        h1 {
            font-size: 2.8rem;
            margin-bottom: 15px;
            color: #3498db;
            text-shadow: 0 0 15px rgba(52, 152, 219, 0.6);
        }
        
        .description {
            font-size: 1.2rem;
            max-width: 900px;
            margin: 0 auto;
            line-height: 1.6;
            color: #bdc3c7;
        }
        
        .main-content {
            display: flex;
            flex-wrap: wrap;
            gap: 25px;
            margin-bottom: 30px;
        }
        
        .simulation-container {
            flex: 2;
            min-width: 300px;
            display: flex;
            flex-direction: column;
            gap: 25px;
        }
        
        .canvas-container {
            background: rgba(13, 27, 42, 0.7);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
            border: 1px solid #3498db;
        }
        
        .canvas-title {
            text-align: center;
            margin-bottom: 18px;
            font-size: 1.5rem;
            color: #3498db;
            font-weight: bold;
            text-shadow: 0 0 8px rgba(52, 152, 219, 0.4);
        }
        
        canvas {
            width: 100%;
            background: #0d1b2a;
            border-radius: 12px;
            margin-bottom: 18px;
            display: block;
            border: 1px solid #2c5282;
        }
        
        #pn-junction-canvas {
            height: 350px;
        }
        
        #energy-band-canvas {
            height: 400px;
        }
        
        #laser-canvas {
            height: 300px;
        }
        
        .semiconductor-canvas {
            height: 250px;
            margin-bottom: 20px;
        }
        
        .value-display {
            display: flex;
            justify-content: space-between;
            font-size: 1rem;
            color: #ecf0f1;
            padding: 10px;
            font-weight: bold;
            text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
            background: rgba(44, 82, 130, 0.3);
            border-radius: 8px;
            margin: 10px 0;
        }
        
        .controls {
            flex: 1;
            min-width: 300px;
            background: rgba(13, 27, 42, 0.7);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
            border: 1px solid #3498db;
        }
        
        .control-group {
            margin-bottom: 22px;
        }
        
        h2 {
            font-size: 1.5rem;
            margin-bottom: 18px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 8px;
            color: #3498db;
            text-shadow: 0 0 8px rgba(52, 152, 219, 0.3);
        }
        
        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 500;
            font-size: 1.1rem;
            color: #ecf0f1;
        }
        
        input[type="range"] {
            width: 100%;
            margin-bottom: 12px;
            -webkit-appearance: none;
            height: 10px;
            border-radius: 5px;
            background: #2c5282;
            outline: none;
        }
        
        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            background: #3498db;
            cursor: pointer;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.7);
        }
        
        select {
            width: 100%;
            padding: 12px;
            border-radius: 8px;
            background: #2c5282;
            color: white;
            border: 1px solid #3498db;
            font-size: 1rem;
            margin-bottom: 15px;
        }
        
        .buttons {
            display: flex;
            gap: 12px;
            margin-top: 22px;
            flex-wrap: wrap;
        }
        
        button {
            padding: 14px 18px;
            border: none;
            border-radius: 10px;
            background: linear-gradient(135deg, #2980b9, #3498db);
            color: white;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            flex: 1;
            font-size: 1rem;
            min-width: 120px;
            box-shadow: 0 4px 15px rgba(41, 128, 185, 0.3);
        }
        
        button:hover {
            background: linear-gradient(135deg, #3498db, #2980b9);
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(41, 128, 185, 0.4);
        }
        
        #play-pause-btn {
            background: linear-gradient(135deg, #27ae60, #2ecc71);
        }
        
        #reset-btn {
            background: linear-gradient(135deg, #c0392b, #e74c3c);
        }
        
        #laser-mode-btn {
            background: linear-gradient(135deg, #9b59b6, #8e44ad);
        }
        
        .info-panel {
            background: rgba(13, 27, 42, 0.7);
            border-radius: 15px;
            padding: 25px;
            margin-top: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
            border: 1px solid #3498db;
        }
        
        .info-content {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 22px;
        }
        
        .info-box {
            background: rgba(44, 82, 130, 0.4);
            padding: 18px;
            border-radius: 12px;
            border: 1px solid #3498db;
        }
        
        .info-box h3 {
            font-size: 1.2rem;
            margin-bottom: 12px;
            color: #3498db;
            text-shadow: 0 0 8px rgba(52, 152, 219, 0.3);
        }
        
        .info-box p {
            line-height: 1.5;
            font-size: 1rem;
            color: #ecf0f1;
        }
        
        .process-description {
            margin-top: 18px;
            padding: 18px;
            background: rgba(44, 82, 130, 0.4);
            border-radius: 12px;
            font-size: 1rem;
            line-height: 1.6;
            border: 1px solid #3498db;
        }
        
        .semiconductor-types {
            display: flex;
            justify-content: space-between;
            margin: 22px 0;
            gap: 15px;
        }
        
        .semiconductor-type {
            width: 32%;
            text-align: center;
            padding: 15px;
            background: rgba(44, 82, 130, 0.4);
            border-radius: 12px;
            border: 1px solid #3498db;
        }
        
        .animation-controls {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }
        
        .animation-btn {
            padding: 10px 14px;
            font-size: 0.9rem;
            min-width: auto;
            background: linear-gradient(135deg, #2980b9, #3498db);
        }
        
        .legend {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin: 15px 0;
            padding: 12px;
            background: rgba(44, 82, 130, 0.3);
            border-radius: 8px;
            border: 1px solid #3498db;
            flex-wrap: wrap;
        }
        
        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 0.9rem;
        }
        
        .legend-color {
            width: 16px;
            height: 16px;
            border-radius: 50%;
            border: 2px solid white;
        }
        
        .laser-controls {
            display: flex;
            gap: 15px;
            margin: 15px 0;
        }
        
        .voltage-display {
            background: rgba(44, 82, 130, 0.4);
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #3498db;
            text-align: center;
            flex: 1;
        }
        
        .voltage-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #3498db;
            margin: 5px 0;
        }
        
        .population-display {
            background: rgba(44, 82, 130, 0.4);
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #3498db;
            text-align: center;
            flex: 1;
        }
        
        .population-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2ecc71;
            margin: 5px 0;
        }
        
        @media (max-width: 1200px) {
            .main-content {
                flex-direction: column;
            }
            
            .semiconductor-types {
                flex-direction: column;
            }
            
            .semiconductor-type {
                width: 100%;
            }
        }
        
        @media (max-width: 768px) {
            .buttons {
                flex-direction: column;
            }
            
            button {
                width: 100%;
            }
            
            .legend {
                flex-direction: column;
                gap: 10px;
            }
            
            .laser-controls {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>半导体PN结与激光器原理</h1>
            <p class="description">
                本界面展示了PN结形成过程、能带结构以及半导体激光器的工作原理，包括粒子数翻转和受激辐射过程。
            </p>
        </header>
        
        <div class="main-content">
            <div class="simulation-container">
                <div class="canvas-container">
                    <h2 class="canvas-title">半导体类型</h2>
                    
                    <div class="semiconductor-types">
                        <div class="semiconductor-type">
                            <h3>本征半导体</h3>
                            <canvas id="intrinsic-canvas" class="semiconductor-canvas"></canvas>
                            <p>电子=空穴</p>
                        </div>
                        <div class="semiconductor-type">
                            <h3>P型半导体</h3>
                            <canvas id="p-type-canvas" class="semiconductor-canvas"></canvas>
                            <p>空穴>电子</p>
                        </div>
                        <div class="semiconductor-type">
                            <h3>N型半导体</h3>
                            <canvas id="n-type-canvas" class="semiconductor-canvas"></canvas>
                            <p>电子>空穴</p>
                        </div>
                    </div>
                    
                    <h2 class="canvas-title">PN结半导体结构</h2>
                    
                    <div class="legend">
                        <div class="legend-item">
                            <div class="legend-color" style="background: #3498db;"></div>
                            <span>P型半导体区域</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #e74c3c;"></div>
                            <span>N型半导体区域</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #7f8c8d;"></div>
                            <span>耗尽层区域</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #f1c40f;"></div>
                            <span>空穴 (+) - P区多数载流子</span>
                        </div>
                        <div class="legend-item">
                            <div class="legend-color" style="background: #9b59b6;"></div>
                            <span>电子 (-) - N区多数载流子</span>
                        </div>
                    </div>
                    
                    <canvas id="pn-junction-canvas"></canvas>
                    <div class="value-display">
                        <span>P型半导体</span>
                        <span>耗尽层宽度: <span id="depletion-width">0.5μm</span></span>
                        <span>N型半导体</span>
                    </div>
                </div>
                
                <div class="canvas-container">
                    <h2 class="canvas-title">PN结能带图与激光器工作原理</h2>
                    <canvas id="energy-band-canvas"></canvas>
                    <div class="value-display">
                        <span>价带</span>
                        <span>禁带宽度: <span id="band-gap">1.12eV</span></span>
                        <span>导带</span>
                    </div>
                    
                    <div class="laser-controls">
                        <div class="voltage-display">
                            <h4>偏置电压</h4>
                            <div class="voltage-value" id="voltage-value">0.0 V</div>
                            <input type="range" id="voltage-control" min="0" max="20" value="0" step="0.5">
                        </div>
                        
                        <div class="population-display">
                            <h4>粒子数分布</h4>
                            <div class="population-value" id="population-ratio">1:1</div>
                            <div id="population-state">热平衡状态</div>
                        </div>
                    </div>
                </div>
                
                <div class="canvas-container">
                    <h2 class="canvas-title">半导体激光器工作原理</h2>
                    <canvas id="laser-canvas"></canvas>
                    <div class="value-display">
                        <span>激发状态</span>
                        <span>激光输出: <span id="laser-output">0 mW</span></span>
                        <span>粒子数翻转: <span id="inversion-ratio">0%</span></span>
                    </div>
                </div>
            </div>
            
            <div class="controls">
                <h2>参数控制</h2>
                
                <div class="control-group">
                    <label for="operation-mode">工作模式</label>
                    <select id="operation-mode">
                        <option value="pn-junction">PN结形成</option>
                        <option value="laser">激光器工作原理</option>
                    </select>
                </div>
                
                <div class="control-group">
                    <label for="p-doping">P型掺杂浓度 (Na)</label>
                    <input type="range" id="p-doping" min="15" max="20" value="16" step="0.1">
                    <div class="value-display">
                        <span>10¹⁵/cm³</span>
                        <span id="p-doping-value">10¹⁶/cm³</span>
                        <span>10²⁰/cm³</span>
                    </div>
                </div>
                
                <div class="control-group">
                    <label for="n-doping">N型掺杂浓度 (Nd)</label>
                    <input type="range" id="n-doping" min="15" max="20" value="16" step="0.1">
                    <div class="value-display">
                        <span>10¹⁵/cm³</span>
                        <span id="n-doping-value">10¹⁶/cm³</span>
                        <span>10²⁰/cm³</span>
                    </div>
                </div>
                
                <div class="control-group">
                    <label for="material">半导体材料</label>
                    <select id="material">
                        <option value="si">硅 (Si) - 禁带宽度: 1.12eV</option>
                        <option value="gaas" selected>砷化镓 (GaAs) - 禁带宽度: 1.43eV</option>
                        <option value="ingap">铟镓磷 (InGaP) - 禁带宽度: 1.9eV</option>
                    </select>
                </div>
                
                <div class="buttons">
                    <button id="prev-btn">上一步</button>
                    <button id="play-pause-btn">▶ 完整运行</button>
                    <button id="next-btn">下一步</button>
                    <button id="laser-mode-btn">激光模式</button>
                    <button id="reset-btn">重置</button>
                </div>
                
                <div class="process-description" id="process-description">
                    <h3>PN结形成步骤: 1/5</h3>
                    <p>当前阶段: <strong>分离状态</strong></p>
                    <p>P型和N型半导体尚未接触，各自保持电中性</p>
                </div>
                
                <div class="laser-explanation" id="laser-explanation" style="display: none; margin-top: 20px; padding: 15px; background: rgba(44, 82, 130, 0.4); border-radius: 10px; border: 1px solid #9b59b6;">
                    <h3 style="color: #9b59b6;">激光器工作原理</h3>
                    <p>1. <strong>正向偏置</strong>: 施加电压降低势垒</p>
                    <p>2. <strong>载流子注入</strong>: 电子和空穴向耗尽区注入</p>
                    <p>3. <strong>粒子数翻转</strong>: 导带电子数 > 价带空穴数</p>
                    <p>4. <strong>受激辐射</strong>: 光子激发相同频率的新光子</p>
                    <p>5. <strong>激光产生</strong>: 光子在谐振腔内放大形成激光</p>
                </div>
            </div>
        </div>
        
        <div class="info-panel">
            <h2>特性信息</h2>
            <div class="info-content">
                <div class="info-box">
                    <h3>内建电势</h3>
                    <p>V<sub>bi</sub> = <span id="built-in-potential">0.7V</span></p>
                    <p>由费米能级差引起，与掺杂浓度有关。</p>
                </div>
                
                <div class="info-box">
                    <h3>耗尽层宽度</h3>
                    <p>W = <span id="depletion-width-value">0.5μm</span></p>
                    <p>空间电荷区的宽度，影响激光器性能。</p>
                </div>
                
                <div class="info-box">
                    <h3>激光阈值</h3>
                    <p>I<sub>th</sub> = <span id="laser-threshold">15mA</span></p>
                    <p>产生激光所需的最小注入电流。</p>
                </div>
                
                <div class="info-box">
                    <h3>发射波长</h3>
                    <p>λ = <span id="emission-wavelength">850nm</span></p>
                    <p>由半导体材料的禁带宽度决定。</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let pDoping = 16;
        let nDoping = 16;
        let material = 'gaas';
        let currentStep = 0;
        let isPlaying = false;
        let isLaserMode = false;
        let voltage = 0;
        let populationInversion = 0;
        let laserOutput = 0;
        const totalSteps = 5;
        let animationInterval = null;
        let autoPlayInterval = null;
        
        const bandGaps = {
            'si': 1.12,
            'gaas': 1.43,
            'ingap': 1.9
        };

        const emissionWavelengths = {
            'si': 1100,
            'gaas': 850,
            'ingap': 650
        };

        // 初始化函数
        function init() {
            initCanvas();
            initEvents();
            updateStepDisplay();
            startCarrierAnimation();
            updateLaserInfo();
        }

        // 初始化Canvas
        function initCanvas() {
            const canvases = [
                'intrinsic-canvas', 'p-type-canvas', 'n-type-canvas', 
                'pn-junction-canvas', 'energy-band-canvas', 'laser-canvas'
            ];
            
            canvases.forEach(canvasId => {
                const canvas = document.getElementById(canvasId);
                canvas.width = canvas.offsetWidth;
                canvas.height = canvas.offsetHeight;
            });
            
            drawIntrinsicSemiconductor();
            drawPTypeSemiconductor();
            drawNTypeSemiconductor();
            drawPNJunction();
            drawEnergyBand();
            drawLaserOperation();
            updateInfo();
        }

        // 绘制本征半导体能带图
        function drawIntrinsicSemiconductor() {
            const canvas = document.getElementById('intrinsic-canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            
            ctx.clearRect(0, 0, width, height);
            ctx.fillStyle = '#0d1b2a';
            ctx.fillRect(0, 0, width, height);
            
            const bandGapValue = bandGaps[material] * 30;
            const ecY = height * 0.3;
            const evY = ecY + bandGapValue;
            const efY = ecY + bandGapValue / 2;
            
            // 绘制导带
            ctx.beginPath();
            ctx.moveTo(20, ecY);
            ctx.lineTo(width - 20, ecY);
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            // 绘制价带
            ctx.beginPath();
            ctx.moveTo(20, evY);
            ctx.lineTo(width - 20, evY);
            ctx.strokeStyle = '#e74c3c';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            // 绘制费米能级
            ctx.beginPath();
            ctx.moveTo(20, efY);
            ctx.lineTo(width - 20, efY);
            ctx.strokeStyle = '#f1c40f';
            ctx.setLineDash([5, 3]);
            ctx.lineWidth = 2;
            ctx.stroke();
            ctx.setLineDash([]);
            
            // 绘制电子和空穴
            for (let i = 0; i < 6; i++) {
                const x = 30 + i * ((width - 60) / 5);
                drawCircle(ctx, x, ecY - 15, 4, '#9b59b6', '-', '12px');
                drawCircle(ctx, x, evY + 15, 4, '#f1c40f', '+', '12px');
            }
            
            // 标签
            ctx.fillStyle = '#ecf0f1';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'left';
            ctx.fillText('导带 (Ec)', 5, ecY - 20);
            ctx.fillText('价带 (Ev)', 5, evY + 25);
            ctx.textAlign = 'right';
            ctx.fillText('费米能级 (Ef)', width - 5, efY - 5);
            ctx.textAlign = 'center';
            ctx.fillText('本征半导体', width / 2, height - 10);
        }

        // 绘制P型半导体能带图
        function drawPTypeSemiconductor() {
            const canvas = document.getElementById('p-type-canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            
            ctx.clearRect(0, 0, width, height);
            ctx.fillStyle = '#0d1b2a';
            ctx.fillRect(0, 0, width, height);
            
            const bandGapValue = bandGaps[material] * 30;
            const ecY = height * 0.3;
            const evY = ecY + bandGapValue;
            const fermiLevel = calculateFermiLevel('p');
            const efY = ecY + bandGapValue * fermiLevel;
            
            // 绘制能带
            ctx.beginPath();
            ctx.moveTo(20, ecY);
            ctx.lineTo(width - 20, ecY);
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(20, evY);
            ctx.lineTo(width - 20, evY);
            ctx.strokeStyle = '#e74c3c';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            // 费米能级
            ctx.beginPath();
            ctx.moveTo(20, efY);
            ctx.lineTo(width - 20, efY);
            ctx.strokeStyle = '#f1c40f';
            ctx.setLineDash([5, 3]);
            ctx.lineWidth = 2;
            ctx.stroke();
            ctx.setLineDash([]);
            
            // 绘制空穴（多数载流子）
            for (let i = 0; i < 8; i++) {
                const x = 25 + i * ((width - 50) / 7);
                drawCircle(ctx, x, evY + 12, 4, '#f1c40f', '+', '12px');
            }
            
            // 绘制电子（少数载流子）
            for (let i = 0; i < 2; i++) {
                const x = width / 2 + i * 20;
                drawCircle(ctx, x, ecY - 12, 4, '#9b59b6', '-', '12px');
            }
            
            // 标签
            ctx.fillStyle = '#ecf0f1';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'left';
            ctx.fillText('导带 (Ec)', 5, ecY - 20);
            ctx.fillText('价带 (Ev)', 5, evY + 25);
            ctx.textAlign = 'right';
            ctx.fillText(`Ef (${(fermiLevel * 100).toFixed(0)}% Ev)`, width - 5, efY - 5);
            ctx.textAlign = 'center';
            ctx.fillText('P型半导体', width / 2, height - 10);
        }

        // 绘制N型半导体能带图
        function drawNTypeSemiconductor() {
            const canvas = document.getElementById('n-type-canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            
            ctx.clearRect(0, 0, width, height);
            ctx.fillStyle = '#0d1b2a';
            ctx.fillRect(0, 0, width, height);
            
            const bandGapValue = bandGaps[material] * 30;
            const ecY = height * 0.3;
            const evY = ecY + bandGapValue;
            const fermiLevel = calculateFermiLevel('n');
            const efY = ecY + bandGapValue * fermiLevel;
            
            // 绘制能带
            ctx.beginPath();
            ctx.moveTo(20, ecY);
            ctx.lineTo(width - 20, ecY);
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(20, evY);
            ctx.lineTo(width - 20, evY);
            ctx.strokeStyle = '#e74c3c';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            // 费米能级
            ctx.beginPath();
            ctx.moveTo(20, efY);
            ctx.lineTo(width - 20, efY);
            ctx.strokeStyle = '#f1c40f';
            ctx.setLineDash([5, 3]);
            ctx.lineWidth = 2;
            ctx.stroke();
            ctx.setLineDash([]);
            
            // 绘制电子（多数载流子）
            for (let i = 0; i < 8; i++) {
                const x = 25 + i * ((width - 50) / 7);
                drawCircle(ctx, x, ecY - 12, 4, '#9b59b6', '-', '12px');
            }
            
            // 绘制空穴（少数载流子）
            for (let i = 0; i < 2; i++) {
                const x = width / 2 + i * 20;
                drawCircle(ctx, x, evY + 12, 4, '#f1c40f', '+', '12px');
            }
            
            // 标签
            ctx.fillStyle = '#ecf0f1';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'left';
            ctx.fillText('导带 (Ec)', 5, ecY - 20);
            ctx.fillText('价带 (Ev)', 5, evY + 25);
            ctx.textAlign = 'right';
            ctx.fillText(`Ef (${((1-fermiLevel) * 100).toFixed(0)}% Ec)`, width - 5, efY - 5);
            ctx.textAlign = 'center';
            ctx.fillText('N型半导体', width / 2, height - 10);
        }

        // 绘制PN结能带图（添加电压偏置效果）
        function drawEnergyBand() {
            const canvas = document.getElementById('energy-band-canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            
            ctx.clearRect(0, 0, width, height);
            ctx.fillStyle = '#0d1b2a';
            ctx.fillRect(0, 0, width, height);
            
            const bandGapValue = bandGaps[material] * 30;
            const junctionX = width / 2;
            let depletionWidth, pEcY, pEvY, nEcY, nEvY;
            
            if (isLaserMode && voltage > 0) {
                // 正向偏置状态
                depletionWidth = Math.max(width / 8 - voltage * 2, width / 20);
                pEcY = height * 0.35;
                pEvY = pEcY + bandGapValue;
                nEcY = height * 0.35;
                nEvY = nEcY + bandGapValue;
            } else {
                // 热平衡状态
                depletionWidth = width / 5;
                pEcY = height * 0.3;
                pEvY = pEcY + bandGapValue;
                nEcY = height * 0.4;
                nEvY = nEcY + bandGapValue;
            }
            
            // 绘制P区能带
            ctx.beginPath();
            ctx.moveTo(20, pEcY);
            ctx.lineTo(junctionX - depletionWidth, pEcY);
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(20, pEvY);
            ctx.lineTo(junctionX - depletionWidth, pEvY);
            ctx.strokeStyle = '#e74c3c';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            // 绘制N区能带
            ctx.beginPath();
            ctx.moveTo(junctionX + depletionWidth, nEcY);
            ctx.lineTo(width - 20, nEcY);
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(junctionX + depletionWidth, nEvY);
            ctx.lineTo(width - 20, nEvY);
            ctx.strokeStyle = '#e74c3c';
            ctx.lineWidth = 3;
            ctx.stroke();
            
            // 绘制耗尽区能带弯曲
            if (currentStep > 0 || isLaserMode) {
                const curveIntensity = isLaserMode ? 1 : currentStep / 4;
                
                ctx.beginPath();
                ctx.moveTo(junctionX - depletionWidth, pEcY);
                ctx.bezierCurveTo(
                    junctionX - depletionWidth/2, pEcY + 20 * curveIntensity,
                    junctionX + depletionWidth/2, nEcY - 20 * curveIntensity,
                    junctionX + depletionWidth, nEcY
                );
                ctx.strokeStyle = '#3498db';
                ctx.lineWidth = 3;
                ctx.stroke();
                
                ctx.beginPath();
                ctx.moveTo(junctionX - depletionWidth, pEvY);
                ctx.bezierCurveTo(
                    junctionX - depletionWidth/2, pEvY + 20 * curveIntensity,
                    junctionX + depletionWidth/2, nEvY - 20 * curveIntensity,
                    junctionX + depletionWidth, nEvY
                );
                ctx.strokeStyle = '#e74c3c';
                ctx.lineWidth = 3;
                ctx.stroke();
            }
            
            // 绘制费米能级
            const fermiLevel = 0.5;
            const efY = pEvY - bandGapValue * fermiLevel;
            ctx.beginPath();
            ctx.moveTo(20, efY);
            ctx.lineTo(width - 20, efY);
            ctx.strokeStyle = '#f1c40f';
            ctx.setLineDash([5, 3]);
            ctx.lineWidth = 2;
            ctx.stroke();
            ctx.setLineDash([]);
            
            // 绘制载流子
            if (isLaserMode && voltage > 0) {
                drawLaserCarriers(ctx, width, height, pEcY, pEvY, nEcY, nEvY, junctionX, depletionWidth);
            } else {
                // 绘制热平衡状态载流子
                for (let i = 0; i < 6; i++) {
                    const x = 30 + i * ((width - 60) / 5);
                    drawCircle(ctx, x, pEcY - 12, 4, '#9b59b6', '-', '12px');
                    drawCircle(ctx, x, pEvY + 12, 4, '#f1c40f', '+', '12px');
                }
            }
            
            // 绘制电压指示
            if (isLaserMode) {
                ctx.fillStyle = '#3498db';
                ctx.font = 'bold 16px Arial';
                ctx.textAlign = 'center';
                ctx.fillText(`正向偏置电压: ${voltage.toFixed(1)}V`, width / 2, 30);
                
                if (voltage > 1.0) {
                    ctx.fillStyle = '#2ecc71';
                    ctx.fillText('粒子数翻转 achieved!', width / 2, 55);
                }
            }
            
            // 标签
            ctx.fillStyle = '#ecf0f1';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('P区', width/4, height - 15);
            ctx.fillText('耗尽区', width/2, height - 15);
            ctx.fillText('N区', width*3/4, height - 15);
            
            ctx.textAlign = 'left';
            ctx.fillText('导带', 10, pEcY - 5);
            ctx.fillText('价带', 10, pEvY + 15);
            ctx.textAlign = 'right';
            ctx.fillText('费米能级', width - 10, efY - 5);
        }

        // 绘制激光器载流子分布
        function drawLaserCarriers(ctx, width, height, pEcY, pEvY, nEcY, nEvY, junctionX, depletionWidth) {
            const inversionFactor = Math.min(voltage / 2, 1);
            
            // 绘制导带电子（大量）
            for (let i = 0; i < 8 + Math.floor(6 * inversionFactor); i++) {
                const x = 30 + i * ((width - 60) / 13);
                drawCircle(ctx, x, pEcY - 12, 4, '#9b59b6', '-', '12px');
            }
            
            // 绘制价带空穴（较少）
            for (let i = 0; i < 8 - Math.floor(6 * inversionFactor); i++) {
                const x = 30 + i * ((width - 60) / 13);
                drawCircle(ctx, x, pEvY + 12, 4, '#f1c40f', '+', '12px');
            }
            
            // 绘制受激辐射过程
            if (voltage > 1.0) {
                for (let i = 0; i < 3; i++) {
                    const x = junctionX;
                    const y = pEcY + (pEvY - pEcY) * 0.3 * (i + 1);
                    drawPhoton(ctx, x, y, '#ff3366');
                }
            }
        }

        // 绘制光子
        function drawPhoton(ctx, x, y, color) {
            ctx.beginPath();
            ctx.arc(x, y, 3, 0, Math.PI * 2);
            ctx.fillStyle = color;
            ctx.fill();
            
            // 绘制光波
            ctx.beginPath();
            ctx.arc(x, y, 8, 0, Math.PI * 2);
            ctx.strokeStyle = color;
            ctx.lineWidth = 1;
            ctx.setLineDash([2, 2]);
            ctx.stroke();
            ctx.setLineDash([]);
        }

        // 绘制激光器工作原理
        function drawLaserOperation() {
            const canvas = document.getElementById('laser-canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            
            ctx.clearRect(0, 0, width, height);
            ctx.fillStyle = '#0d1b2a';
            ctx.fillRect(0, 0, width, height);
            
            // 绘制激光器结构
            const cavityWidth = width * 0.8;
            const cavityHeight = height * 0.6;
            const cavityX = (width - cavityWidth) / 2;
            const cavityY = (height - cavityHeight) / 2;
            
            // 激光谐振腔
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 2;
            ctx.strokeRect(cavityX, cavityY, cavityWidth, cavityHeight);
            
            // 反射镜
            ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
            ctx.fillRect(cavityX, cavityY, 5, cavityHeight);
            ctx.fillRect(cavityX + cavityWidth - 5, cavityY, 5, cavityHeight);
            
            // 绘制有源区
            ctx.fillStyle = `rgba(52, 152, 219, ${0.3 + voltage * 0.05})`;
            ctx.fillRect(cavityX + 10, cavityY + 10, cavityWidth - 20, cavityHeight - 20);
            
            // 绘制激光
            if (voltage > 1.0) {
                const laserIntensity = Math.min((voltage - 1) * 50, 100);
                ctx.fillStyle = `rgba(255, 51, 102, ${laserIntensity / 100})`;
                
                // 激光光束
                ctx.beginPath();
                ctx.moveTo(cavityX + cavityWidth, cavityY + cavityHeight / 2);
                ctx.lineTo(width, cavityY + cavityHeight / 2 - 20);
                ctx.lineTo(width, cavityY + cavityHeight / 2 + 20);
                ctx.closePath();
                ctx.fill();
                
                // 激光输出文字
                ctx.fillStyle = '#ff3366';
                ctx.font = 'bold 16px Arial';
                ctx.fillText(`激光输出: ${laserOutput.toFixed(1)}mW`, width * 0.7, cavityY - 10);
            }
            
            // 标题
            ctx.fillStyle = '#ecf0f1';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('半导体激光器谐振腔', width / 2, 20);
        }

        // 绘制PN结半导体结构
        function drawPNJunction() {
            const canvas = document.getElementById('pn-junction-canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            const junctionX = width / 2;
            const depletionWidth = calculateDepletionWidth() / 100 * (width/3);
            
            ctx.clearRect(0, 0, width, height);
            
            // 绘制P型区域（蓝色）
            const pGradient = ctx.createLinearGradient(0, 0, junctionX - depletionWidth, 0);
            pGradient.addColorStop(0, '#2980b9');
            pGradient.addColorStop(1, '#3498db');
            ctx.fillStyle = pGradient;
            ctx.fillRect(0, height/2 - 80, junctionX - depletionWidth, 160);
            
            // 绘制N型区域（红色）
            const nGradient = ctx.createLinearGradient(junctionX + depletionWidth, 0, width, 0);
            nGradient.addColorStop(0, '#c0392b');
            nGradient.addColorStop(1, '#e74c3c');
            ctx.fillStyle = nGradient;
            ctx.fillRect(junctionX + depletionWidth, height/2 - 80, width - junctionX - depletionWidth, 160);
            
            // 绘制耗尽层（灰色）
            const depletionGradient = ctx.createLinearGradient(junctionX - depletionWidth, 0, junctionX + depletionWidth, 0);
            depletionGradient.addColorStop(0, '#7f8c8d');
            depletionGradient.addColorStop(0.5, '#95a5a6');
            depletionGradient.addColorStop(1, '#7f8c8d');
            ctx.fillStyle = depletionGradient;
            ctx.fillRect(junctionX - depletionWidth, height/2 - 80, depletionWidth * 2, 160);
            
            // 绘制界面线
            ctx.strokeStyle = '#f1c40f';
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(junctionX, height/2 - 100);
            ctx.lineTo(junctionX, height/2 + 100);
            ctx.stroke();
            
            // 绘制静态载流子
            for (let i = 0; i < 12; i++) {
                const x = Math.random() * (junctionX - depletionWidth - 40) + 20;
                const y = Math.random() * 120 + (height/2 - 60);
                drawCircle(ctx, x, y, 5, '#f1c40f', '+', '14px');
            }
            
            for (let i = 0; i < 12; i++) {
                const x = Math.random() * (width - junctionX - depletionWidth - 40) + junctionX + depletionWidth + 20;
                const y = Math.random() * 120 + (height/2 - 60);
                drawCircle(ctx, x, y, 5, '#9b59b6', '-', '14px');
            }
            
            // 标签
            ctx.fillStyle = '#ecf0f1';
            ctx.font = 'bold 16px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('P型半导体', junctionX/2, height/2 - 100);
            ctx.fillText('N型半导体', junctionX + (width - junctionX)/2, height/2 - 100);
            ctx.fillText('耗尽层', junctionX, height/2 - 100);
        }

        // 启动载流子运动动画
        function startCarrierAnimation() {
            if (animationInterval) clearInterval(animationInterval);
            
            animationInterval = setInterval(() => {
                animateCarriers();
            }, 100);
        }

        // 动画载流子运动
        function animateCarriers() {
            const canvas = document.getElementById('pn-junction-canvas');
            const ctx = canvas.getContext('2d');
            const width = canvas.width;
            const height = canvas.height;
            const junctionX = width / 2;
            const depletionWidth = calculateDepletionWidth() / 100 * (width/3);
            
            // 重绘背景
            drawPNJunction();
            
            const now = Date.now();
            
            // P区空穴向界面移动（黄色）
            for (let i = 0; i < 4; i++) {
                const progress = (Math.sin(now/1000 + i) + 1) / 2;
                const x = junctionX - depletionWidth - 30 - progress * (junctionX - depletionWidth - 60);
                const y = height/2 - 50 + i * 30;
                drawCircle(ctx, x, y, 6, '#f1c40f', '+', '16px');
            }
            
            // N区电子向界面移动（紫色）
            for (let i = 0; i < 4; i++) {
                const progress = (Math.cos(now/1000 + i) + 1) / 2;
                const x = junctionX + depletionWidth + 30 + progress * (width - junctionX - depletionWidth - 60);
                const y = height/2 - 50 + i * 30;
                drawCircle(ctx, x, y, 6, '#9b59b6', '-', '16px');
            }
            
            // 耗尽区中的载流子（白色，表示被束缚的离子）
            for (let i = 0; i < 3; i++) {
                const x = junctionX - depletionWidth + (i + 1) * (depletionWidth * 2 / 4);
                const y = height/2 - 40 + Math.sin(now/500 + i) * 15;
                drawCircle(ctx, x, y, 5, '#ecf0f1', '', '12px');
            }
        }

        // 绘制圆形
        function drawCircle(ctx, x, y, radius, color, symbol, fontSize = '12px') {
            ctx.beginPath();
            ctx.arc(x, y, radius, 0, Math.PI * 2);
            ctx.fillStyle = color;
            ctx.fill();
            
            if (symbol) {
                ctx.fillStyle = '#2c3e50';
                ctx.font = `bold ${fontSize} Arial`;
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillText(symbol, x, y);
            }
        }

        // 计算费米能级位置
        function calculateFermiLevel(type) {
            const doping = type === 'p' ? pDoping : nDoping;
            const minDoping = 15;
            const maxDoping = 20;
            const normalizedDoping = (doping - minDoping) / (maxDoping - minDoping);
            
            if (type === 'p') {
                return 0.1 + 0.2 * normalizedDoping;
            } else {
                return 0.7 + 0.2 * normalizedDoping;
            }
        }

        // 计算耗尽层宽度
        function calculateDepletionWidth() {
            return 50 + (Math.abs(pDoping - nDoping) * 5);
        }

        // 更新信息显示
        function updateInfo() {
            document.getElementById('p-doping-value').textContent = `10^${pDoping.toFixed(1)}/cm³`;
            document.getElementById('n-doping-value').textContent = `10^${nDoping.toFixed(1)}/cm³`;
            
            const bandGapValue = bandGaps[material];
            document.getElementById('band-gap').textContent = `${bandGapValue}eV`;
            
            const depletionWidth = calculateDepletionWidth() / 100 * 2.5;
            document.getElementById('depletion-width').textContent = `${depletionWidth.toFixed(2)}μm`;
            document.getElementById('depletion-width-value').textContent = `${depletionWidth.toFixed(2)}μm`;
            
            const Vbi = 0.7 + (Math.abs(pDoping - nDoping) * 0.05);
            document.getElementById('built-in-potential').textContent = `${Vbi.toFixed(2)}V`;
        }

        // 更新激光器信息
        function updateLaserInfo() {
            document.getElementById('voltage-value').textContent = `${voltage.toFixed(1)} V`;
            
            // 计算粒子数比例
            const inversion = Math.min(voltage / 2, 1);
            populationInversion = inversion;
            const electronCount = Math.floor(8 + 6 * inversion);
            const holeCount = Math.floor(8 - 6 * inversion);
            
            document.getElementById('population-ratio').textContent = `${electronCount}:${holeCount}`;
            document.getElementById('population-state').textContent = 
                inversion > 0.5 ? '粒子数翻转!' : '热平衡状态';
            
            // 计算激光输出
            laserOutput = voltage > 1.0 ? Math.pow(voltage - 1, 2) * 50 : 0;
            document.getElementById('laser-output').textContent = `${laserOutput.toFixed(1)} mW`;
            document.getElementById('inversion-ratio').textContent = `${Math.round(populationInversion * 100)}%`;
            
            // 更新激光器特定信息
            document.getElementById('laser-threshold').textContent = '15mA';
            document.getElementById('emission-wavelength').textContent = `${emissionWavelengths[material]}nm`;
        }

        // 更新步骤显示
        function updateStepDisplay() {
            const steps = ['分离状态', '开始接触', '扩散运动', '形成耗尽层', '热平衡'];
            const descriptions = [
                'P型和N型半导体尚未接触，各自保持电中性',
                'P型和N型半导体开始接触，载流子开始扩散',
                '多数载流子向对方区域扩散，形成扩散电流',
                '形成空间电荷区和内建电场，阻止进一步扩散',
                '扩散运动和漂移运动达到平衡，形成稳定的PN结'
            ];
            
            document.getElementById('process-description').innerHTML = `
                <h3>PN结形成步骤: ${currentStep + 1}/${totalSteps}</h3>
                <p>当前阶段: <strong>${steps[currentStep]}</strong></p>
                <p>${descriptions[currentStep]}</p>
            `;
            
            // 重绘能带图以反映当前步骤
            drawEnergyBand();
        }

        // 上一步按钮功能
        function prevStep() {
            if (currentStep > 0) {
                currentStep--;
                updateStepDisplay();
            } else {
                alert('已经是第一步了');
            }
        }

        // 下一步按钮功能
        function nextStep() {
            if (currentStep < totalSteps - 1) {
                currentStep++;
                updateStepDisplay();
            } else {
                alert('已经是最后一步了');
            }
        }

        // 播放/暂停按钮功能
        function togglePlayPause() {
            const btn = document.getElementById('play-pause-btn');
            isPlaying = !isPlaying;
            
            if (isPlaying) {
                btn.textContent = '❚❚ 暂停';
                if (autoPlayInterval) clearInterval(autoPlayInterval);
                // 自动播放逻辑
                autoPlayInterval = setInterval(() => {
                    if (currentStep < totalSteps - 1) {
                        currentStep++;
                        updateStepDisplay();
                    } else {
                        clearInterval(autoPlayInterval);
                        isPlaying = false;
                        btn.textContent = '▶ 完整运行';
                    }
                }, 2000);
            } else {
                btn.textContent = '▶ 继续';
                if (autoPlayInterval) clearInterval(autoPlayInterval);
            }
        }

        // 激光模式切换
        function toggleLaserMode() {
            isLaserMode = !isLaserMode;
            const btn = document.getElementById('laser-mode-btn');
            const explanation = document.getElementById('laser-explanation');
            const modeSelect = document.getElementById('operation-mode');
            
            if (isLaserMode) {
                btn.textContent = 'PN结模式';
                btn.style.background = 'linear-gradient(135deg, #2980b9, #3498db)';
                explanation.style.display = 'block';
                modeSelect.value = 'laser';
                voltage = 0;
                updateLaserInfo();
            } else {
                btn.textContent = '激光模式';
                btn.style.background = 'linear-gradient(135deg, #9b59b6, #8e44ad)';
                explanation.style.display = 'none';
                modeSelect.value = 'pn-junction';
            }
            
            drawEnergyBand();
            drawLaserOperation();
        }

        // 重置按钮功能
        function resetAll() {
            pDoping = 16;
            nDoping = 16;
            material = 'gaas';
            currentStep = 0;
            isPlaying = false;
            voltage = 0;
            isLaserMode = false;
            
            document.getElementById('p-doping').value = pDoping;
            document.getElementById('n-doping').value = nDoping;
            document.getElementById('material').value = material;
            document.getElementById('voltage-control').value = 0;
            document.getElementById('operation-mode').value = 'pn-junction';
            document.getElementById('play-pause-btn').textContent = '▶ 完整运行';
            document.getElementById('laser-mode-btn').textContent = '激光模式';
            document.getElementById('laser-mode-btn').style.background = 'linear-gradient(135deg, #9b59b6, #8e44ad)';
            document.getElementById('laser-explanation').style.display = 'none';
            
            if (autoPlayInterval) clearInterval(autoPlayInterval);
            initCanvas();
            updateStepDisplay();
            updateLaserInfo();
        }

        // 初始化事件监听
        function initEvents() {
            // 掺杂浓度控制
            document.getElementById('p-doping').addEventListener('input', function() {
                pDoping = parseFloat(this.value);
                updateInfo();
                drawPTypeSemiconductor();
                drawPNJunction();
                drawEnergyBand();
            });
            
            document.getElementById('n-doping').addEventListener('input', function() {
                nDoping = parseFloat(this.value);
                updateInfo();
                drawNTypeSemiconductor();
                drawPNJunction();
                drawEnergyBand();
            });
            
            // 材料选择
            document.getElementById('material').addEventListener('change', function() {
                material = this.value;
                updateInfo();
                updateLaserInfo();
                drawIntrinsicSemiconductor();
                drawPTypeSemiconductor();
                drawNTypeSemiconductor();
                drawEnergyBand();
                drawLaserOperation();
            });
            
            // 电压控制
            document.getElementById('voltage-control').addEventListener('input', function() {
                voltage = parseFloat(this.value) / 2;
                updateLaserInfo();
                drawEnergyBand();
                drawLaserOperation();
            });
            
            // 工作模式选择
            document.getElementById('operation-mode').addEventListener('change', function() {
                if (this.value === 'laser' && !isLaserMode) {
                    toggleLaserMode();
                } else if (this.value === 'pn-junction' && isLaserMode) {
                    toggleLaserMode();
                }
            });
            
            // 按钮事件
            document.getElementById('prev-btn').addEventListener('click', prevStep);
            document.getElementById('next-btn').addEventListener('click', nextStep);
            document.getElementById('play-pause-btn').addEventListener('click', togglePlayPause);
            document.getElementById('laser-mode-btn').addEventListener('click', toggleLaserMode);
            document.getElementById('reset-btn').addEventListener('click', resetAll);
        }

        // 窗口调整大小时重置Canvas尺寸
        window.addEventListener('resize', initCanvas);
        
        // 页面加载完成后初始化
        window.addEventListener('load', init);
    </script>
</body>
</html>